Python测试函数出现错误问题解决:AssertionError: None != ‘Janis Joplin‘ |
您所在的位置:网站首页 › python reverse返回none › Python测试函数出现错误问题解决:AssertionError: None != ‘Janis Joplin‘ |
当使用Python测试函数时,可能会出现AsserttionError,即断言错误。 根据错误提示可知,空值不能和测试期望结果Janis Joplin相同,仔细查看 正在测试的函数并没有返回值,也就是所谓的none,所以才会出现错误。 错误函数代码如下: def get_formatted_name(first, last): """获得一个整洁的完整的姓名""" full_name = first+' '+last print(full_name.title())我们发现,单独进行运行代码时,反而没有问题,可是,一旦执行测试代码就会发生断言错误。 测试代码: import unittest from name_function import get_formatted_name class NamesTestCase(unittest.TestCase): """测试函数name_function()""" def test_first_last_name(self): formatted_name = get_formatted_name('janis', 'joplin') self.assertEqual(formatted_name, 'Janis Joplin') if __name__ == '__main__': unittest.main()运行测试代码时会发现traceback: Traceback (most recent call last): File "\test_name_function.py", line 10, in test_first_last_name self.assertEqual(formatted_name, 'Janis Joplin') AssertionError: None != 'Janis Joplin'当我们把欲测试的函数添加一个返回值时,即: def get_formatted_name(first, last): """获得一个整洁的完整的姓名""" full_name = first+' '+last return full_name.title()再重新运行测试代码,就不会发生错误了。 测试结果如下: Ran 1 test in 0.003s OK Process finished with exit code 0注意:这里有的人可能是: . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK这是电脑设置问题,但影响不大,句点的作用就是测试完的个数,结果中已经有了数字1,如果数量多的时候,不会有人去一个个数几个句点吧。 注意:还有会发生不能测试的情况,这里很大可能是unittest调用主函数时,没有条件判断if __name__ == '__main__',即正确代码应为: if __name__ == '__main__': unittest.main()而不是: unittest.main() |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |